package org.uni_hi.lsep.gui.util;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import org.uni_hi.lsep.gui.test.sim.IconContainer;

/**
 * Class that draws an images on its background panel. Used in {@link IconContainer} class.
 * @author Swen
 * @see IconContainer
 */
public abstract class BackgroundImagePanel {

	/** 
	 */
	private static final long serialVersionUID = 1L;
	
	private volatile Image _curImg=null;
	
	private JPanel _panel=null;
	
	/**
	 * Creates a new instance of the {@link BackgroundImagePanel} class. Used to display
	 * an image in the background of the panel. Used in {@link IconContainer}.
	 * @param lm - LayoutManager component used to layout this {@link JPanel}
	 * @param path - the path to the background image as {@link String}
	 */
	public BackgroundImagePanel(LayoutManager lm, String path){
		getPanel().setLayout(lm);
		ImageIcon _img=createImageIcon(path);
		Dimension size=new Dimension(_img.getIconWidth(),_img.getIconHeight());
		getPanel().setPreferredSize(size);
		getPanel().setSize(size);
		setBGImage(_img.getImage());
	}
	
	/**
	 * Returns the {@link JPanel} object, used for display.
	 * @return {@link JPanel} object, used for display.
	 */
	public JPanel getPanel(){
		if(_panel==null){
			_panel=new JPanel(){
				/**	 */
				private static final long serialVersionUID = 8186572982899683424L;

				@Override
				protected void paintChildren(Graphics g){
					g.drawImage(_curImg, 0, 0, this);
					super.paintChildren(g);
				}
			};
			_panel.setOpaque(false);
		}
		return _panel;
	}

	/**
	 * Creates a new instance of the {@link BackgroundImagePanel} class. Used to display
	 * an image in the background of the panel. Used in {@link IconContainer}.
	 * @param path - the path to the background image as {@link String}
	 */
	public BackgroundImagePanel(String path){
		setBGImage(path);
	}
	
	/**
	 * Creates the background image and sets the size of this {@link JPanel}
	 * to be identical with the image bounds.
	 * @param path - path to image file
	 */
	public void setBGImage(String path){
		setBGImage(createImageIcon(path).getImage());
	}
	
	/**
	 * Creates an ImageIcon object from the given path.
	 * @param path - path to an image
	 * @return
	 */
	public ImageIcon createImageIcon(String path){
		return new ImageIcon(path);
	}
	
	/**
	 * Creates the background image and sets the size of this {@link JPanel}
	 * to be identical with the image bounds.
	 * @param i - the {@link ImageIcon} object used as background image
	 */
	public void setBGImage(Image i){
		_curImg=i;
		getPanel().updateUI();
	}
	
	public Image getBGImage(){
		return _curImg;
	}
}
